package com.cskaoyan.config;

import com.cskaoyan.converter.String2UserConverter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

/**
 * @author stone
 * @date 2022/06/01 10:21
 */
@Configuration
public class Converter2Configuration implements WebMvcConfigurer, ApplicationContextAware {

    ApplicationContext applicationContext;

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // 拿到某个类型的所有组件，Map → key：组件id ；value：组件
        Map<String, Converter> converterMap = applicationContext.getBeansOfType(Converter.class);
        Collection<Converter> values = converterMap.values();
        Iterator<Converter> iterator = values.iterator();
        while (iterator.hasNext()) {
            Converter next = iterator.next();
            registry.addConverter(next);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
